<template>
	<div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
		<!-- Background decorations -->
		<div class="absolute inset-0 overflow-hidden pointer-events-none">
			<div
				class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob">
			</div>
			<div
				class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-2000">
			</div>
			<div
				class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-70 animate-blob animation-delay-4000">
			</div>
		</div>

		<!-- Main content area -->
		<div class="container mx-auto px-12 py-10 pt-32 relative z-10">
			<!-- Top: Back button & Title -->
			<div class="flex items-center justify-between mb-10">
				<div class="flex items-center gap-4">
					<el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
						<el-icon class="mr-2 text-xl">
							<ArrowLeft />
						</el-icon>
						返回
					</el-button>
					<h1 class="text-4xl font-bold text-gray-900">作业管理</h1>
				</div>
				<div class="flex items-center gap-4">
					<el-button type="primary" size="large" @click="showSubmitDialog = true" class="rounded-full px-6">
						<el-icon class="mr-2">
							<Plus />
						</el-icon>
						发布作业
					</el-button>
				</div>
			</div>

			<!-- 作业统计卡片 -->
			<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
				<div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
					<div class="flex items-center gap-4">
						<div class="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center">
							<el-icon class="text-blue-600 text-2xl">
								<Document />
							</el-icon>
						</div>
						<div>
							<p class="text-2xl font-bold text-gray-900">{{ homeworkStats.total }}</p>
							<p class="text-gray-600">总作业数量</p>
						</div>
					</div>
				</div>
				<div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-200">
					<div class="flex items-center gap-4">
						<div class="w-16 h-16 bg-purple-100 rounded-xl flex items-center justify-center">
							<el-icon class="text-purple-600 text-2xl">
								<Star />
							</el-icon>
						</div>
						<div>
							<p class="text-2xl font-bold text-gray-900">{{ homeworkStats.graded || 0 }}</p>
							<p class="text-gray-600">已批改</p>
						</div>
					</div>
				</div>
			</div>

			<!-- 作业列表 -->
			<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
				<div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
					<div class="flex items-center justify-between">
						<div class="flex items-center gap-4">
							<div
								class="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center">
								<el-icon class="text-white text-2xl">
									<Notebook />
								</el-icon>
							</div>
							<div>
								<h2 class="text-2xl font-bold text-gray-900">作业列表</h2>
								<p class="text-gray-600">管理所有作业</p>
							</div>
						</div>
						<div class="flex items-center gap-4">
							<el-input v-model="searchKeyword" placeholder="搜索作业..." class="w-64" size="default">
								<template #prefix>
									<el-icon>
										<Search />
									</el-icon>
								</template>
							</el-input>
							<el-select v-model="filterStatus" placeholder="状态筛选" class="w-32" size="default">
								<el-option label="全部" value="" />
								<el-option label="已发布" value="published" />
								<el-option label="未批改" value="ungraded" />
								<el-option label="已批改" value="graded" />
							</el-select>
						</div>
					</div>
				</div>

				<div class="p-8">
					<div class="space-y-6">
						<div v-for="homework in filteredHomeworkList" :key="homework.id"
							class="group p-6 border-2 border-gray-100 rounded-2xl hover:border-blue-300 hover:bg-blue-50 transition-all duration-300 cursor-pointer"
							@click="viewHomeworkDetail(homework)">
							<div class="flex items-center justify-between">
								<div class="flex-1">
									<div class="flex items-center gap-4 mb-4">
										<h4
											class="text-xl font-bold text-gray-900 group-hover:text-blue-600 transition-colors">
											{{ homework.title }}
										</h4>
										<span
											class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium"
											:class="{
                            'bg-yellow-100 text-yellow-800': homework.status === 'published',
                            'bg-blue-100 text-blue-800': homework.status === 'ungraded',
                            'bg-green-100 text-green-800': homework.status === 'graded'
                          }">
											{{ getStatusText(homework.status) }}
										</span>
									</div>
									<p class="text-gray-600 mb-3">
										{{ homework.content || '无描述' }}
									</p>
									<div class="flex items-center gap-6 text-sm text-gray-500">
										<span>截止时间: {{ formatDate(homework.deadline) }}</span>
										<span>发布时间: {{ formatDate(homework.createTime) }}</span>
										<span v-if="homework.submitCount !== undefined"><el-icon class="mr-1"><UserFilled /></el-icon>提交人数: {{ homework.submitCount }}</span>
									</div>
								</div>
								<div class="flex items-center gap-3">
									<el-button type="primary" size="small" @click.stop="handleViewDetail(homework)"
										class="rounded-full">
										查看详情
									</el-button>
									<el-icon class="text-gray-400 group-hover:text-blue-500 transition-colors">
										<ArrowRight />
									</el-icon>
								</div>
							</div>
						</div>

						<!-- 空状态 -->
						<div v-if="filteredHomeworkList.length === 0" class="text-center py-16">
							<div
								class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
								<el-icon class="text-gray-400 text-3xl">
									<Document />
								</el-icon>
							</div>
							<h3 class="text-xl font-medium text-gray-900 mb-2">暂无作业</h3>
							<p class="text-gray-500">当前没有任何作业数据</p>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 提交作业对话框 -->
		<el-dialog v-model="showSubmitDialog" title="发布作业" width="700px" :close-on-click-modal="false">
			<div class="p-4">
				<el-form ref="submitFormRef" :model="submitForm" :rules="submitRules" label-width="100px"
					class="space-y-6">
					<el-form-item label="作业标题" prop="title">
						<el-input v-model="submitForm.title" placeholder="请输入作业标题" class="w-full" size="large" />
					</el-form-item>

					<el-form-item label="截止日期" prop="deadline">
						<el-date-picker v-model="submitForm.deadline" type="date" placeholder="选择截止日期" class="w-full"
							size="large" />
					</el-form-item>

					<el-form-item label="作业详情" prop="description">
						<el-input v-model="submitForm.description" type="textarea" :rows="6"
							placeholder="请详细描述作业要求、内容和评分标准等信息" class="w-full" size="large" />
					</el-form-item>

					<el-form-item label="附件上传">
						<el-upload ref="uploadRef" :auto-upload="false" :on-change="handleFileChange"
							:on-remove="handleFileRemove" :file-list="submitForm.attachments" multiple drag
							class="w-full p-6 border-2 border-dashed border-gray-200 rounded-xl hover:border-blue-300 transition-colors">
							<el-icon class="el-icon--upload text-2xl text-blue-500 mb-2">
								<UploadFilled />
							</el-icon>
							<div class="el-upload__text text-gray-700">
								将文件拖到此处，或<em class="text-blue-600">点击上传</em>
							</div>
							<template #tip>
								<div class="el-upload__tip mt-4 text-sm text-gray-500">
									支持 PDF、Word、图片等格式，单个文件不超过 10MB
								</div>
							</template>
						</el-upload>
					</el-form-item>

				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer flex gap-3">
					<el-button @click="showSubmitDialog = false" size="large" class="px-6">取消</el-button>
					<el-button type="primary" @click="handleSubmit" :loading="submitting" size="large"
						class="px-8">发布作业</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 作业详情对话框 -->
		<el-dialog v-model="showDetailDialog" title="作业详情" width="800px">
			<div v-if="selectedHomework" class="space-y-6">
				<div class="bg-gray-50 rounded-lg p-4">
					<h3 class="text-xl font-bold text-gray-900 mb-3">{{ selectedHomework.title }}</h3>
					<p class="text-gray-600 mb-4">
						{{ selectedHomework.content || '无描述' }}
					</p>
					<div class="grid grid-cols-2 gap-4 text-sm">
						<div>
							<span class="text-gray-500">发布时间:</span>
							<span class="ml-2">{{ formatDate(selectedHomework.createTime) }}</span>
						</div>
						<div>
							<span class="text-gray-500">截止时间:</span>
							<span class="ml-2">{{ formatDate(selectedHomework.deadline) }}</span>
						</div>
						<div>
							<span class="text-gray-500">状态:</span>
							<span class="ml-2">{{ getStatusText(selectedHomework.status) }}</span>
						</div>
						<div v-if="selectedHomework.submitCount !== undefined">
							<span class="text-gray-500"><el-icon class="mr-1"><UserFilled /></el-icon>提交人数:</span>
							<span class="ml-2">{{ selectedHomework.submitCount }}</span>
						</div>
					</div>
				</div>

				<!-- 附件列表 -->
				<div v-if="selectedHomework.attachments && selectedHomework.attachments.length > 0">
					<h4 class="text-lg font-semibold text-gray-800 mb-3">附件</h4>
					<div class="space-y-2">
						<div v-for="(file, index) in selectedHomework.attachments" :key="index"
							class="flex items-center justify-between bg-gray-50 p-3 rounded-lg">
							<div class="flex items-center gap-2">
								<el-icon class="text-gray-500">
									<Document />
								</el-icon>
								<span>{{ file.name }}</span>
							</div>
							<el-button type="text" size="small" @click="downloadFile(file)" class="text-blue-600">
								<el-icon class="mr-1">
									<Download />
								</el-icon>下载
							</el-button>
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		computed,
		ref,
		onMounted
	} from 'vue'
	import {
		useRouter
	} from 'vue-router'
	import {
		ElMessage
	} from 'element-plus'
	import {
		ArrowLeft,
		ArrowRight,
		Plus,
		Document,
		Star,
		Notebook,
		Search,
		UploadFilled,
		Download,
		UserFilled
	} from '@element-plus/icons-vue'
	import axios from 'axios'
	// 引入API
	import {
		getHomeworkList,
		getHomeworkStats,
		publishHomework,
		getHomeworkDetail,
		uploadFiles
	} from '@/api/teacher/homework'

	const router = useRouter()

	// 状态管理
	const showSubmitDialog = ref(false)
	const showDetailDialog = ref(false)
	const selectedHomework = ref(null)
	const submitting = ref(false)
	const submitFormRef = ref()
	const uploadRef = ref()

	// 作业统计数据
	const homeworkStats = ref({
		total: 0,
		graded: 0
	})

	// 作业列表数据 - 确保初始化为数组
	const homeworkList = ref([])

	// 筛选和搜索
	const filterStatus = ref('')
	const searchKeyword = ref('')

	// 筛选作业列表
	const filteredHomeworkList = computed(() => {
		let filtered = [...homeworkList.value] // 确保处理的是数组

		// 状态筛选
		if (filterStatus.value) {
			filtered = filtered.filter(hw => hw.status === filterStatus.value)
		}

		// 关键词搜索
		if (searchKeyword.value) {
			const keyword = searchKeyword.value.toLowerCase()
			filtered = filtered.filter(hw =>
				hw.title.toLowerCase().includes(keyword) ||
				(hw.content && hw.content.toLowerCase().includes(keyword))
			)
		}

		return filtered
	})

	// 提交作业表单数据
	const submitForm = ref({
		title: '',
		description: '',
		deadline: '',
		attachments: []
	})

	const submitRules = {
		title: [{
			required: true,
			message: '请输入作业标题',
			trigger: 'blur'
		}],
		description: [{
			required: true,
			message: '请输入作业描述',
			trigger: 'blur'
		}],
		deadline: [{
			required: true,
			message: '请选择截止日期',
			trigger: 'change'
		}]
	}

	// 文件处理
	const handleFileChange = (file, fileList) => {
		submitForm.value.attachments = fileList
	}

	const handleFileRemove = (file, fileList) => {
		submitForm.value.attachments = fileList
	}

	// 返回上一页
	const goBack = () => {
		router.back()
	}

	// 提交作业
	const handleSubmit = async () => {
		try {
			await submitFormRef.value.validate()
			submitting.value = true

			// 准备提交数据，包含默认值
			const homeworkData = {
				title: submitForm.value.title,
				content: submitForm.value.description,
				// 确保日期格式为标准ISO格式
				deadline: submitForm.value.deadline ? new Date(submitForm.value.deadline).toISOString() : null,
				createTime: new Date().toISOString(),
				// 设置默认值
				classId: "706392",
				teacherId: "2025058"
			}

			console.log("发送的作业数据:", homeworkData); // 调试用

			// 调用API发布作业
			const response = await publishHomework(homeworkData)

			// 检查响应是否成功
			if (response && response.success) {
				ElMessage.success('作业发布成功！')
				showSubmitDialog.value = false

				// 重置表单
				submitForm.value = {
					title: '',
					description: '',
					deadline: '',
					attachments: []
				}
				if (uploadRef.value) {
					uploadRef.value.clearFiles()
				}

				// 重新获取作业列表和统计数据
				fetchHomeworkList()
				fetchHomeworkStats()
			} else {
				ElMessage.error(response?.message || '作业发布失败')
			}
		} catch (error) {
			console.error('发布失败:', error)
			ElMessage.error('发布作业失败，请重试')
		} finally {
			submitting.value = false
		}
	}

	// 查看作业详情
	const viewHomeworkDetail = async (homework) => {
		try {
			// 不传递班级ID
			const response = await getHomeworkDetail(homework.id)
			// 确保正确提取数据
			selectedHomework.value = response.data || homework
			// 为没有状态的作业设置默认状态
			if (!selectedHomework.value.status) {
				selectedHomework.value.status = 'published'
			}
			showDetailDialog.value = true
		} catch (error) {
			console.error('获取作业详情失败:', error)
			ElMessage.error('获取作业详情失败')
		}
	}

	// 处理查看详情
	const handleViewDetail = (homework) => {
		// 为没有状态的作业设置默认状态
		const status = homework.status || 'published'
		switch (status) {
			case 'published':
				ElMessage.info('跳转到提交页面')
				break
			case 'ungraded':
				router.push(`/homework/${homework.id}/grade`)
				break
			case 'graded':
				viewHomeworkDetail(homework)
				break
			default:
				break
		}
	}

	// 下载文件
	const downloadFile = async (file) => {
		try {
			const response = await axios({
				url: file.url,
				method: 'get',
				responseType: 'blob'
			})

			const url = window.URL.createObjectURL(new Blob([response.data]))
			const link = document.createElement('a')
			link.href = url
			link.setAttribute('download', file.name)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			window.URL.revokeObjectURL(url)
		} catch (error) {
			console.error('下载文件失败:', error)
			ElMessage.error('下载文件失败，请重试')
		}
	}

	// 工具函数
	const getStatusText = (status) => {
		// 为未定义的状态设置默认值
		const actualStatus = status || 'published'
		const statusMap = {
			published: '已发布',
			ungraded: '未批改',
			graded: '已批改'
		}
		return statusMap[actualStatus] || actualStatus || '未知状态'
	}

	const formatDate = (dateStr) => {
		if (!dateStr) return '-'
		// 处理不同格式的日期字符串
		const date = new Date(dateStr)
		if (isNaN(date.getTime())) {
			return '-'
		}
		return date.toLocaleDateString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit'
		})
	}

	// 获取作业列表 - 核心修改：确保正确处理后端返回数据
	const fetchHomeworkList = async () => {
		try {
			// 不传递班级ID
			const response = await getHomeworkList()

			// 明确检查并处理响应数据
			if (Array.isArray(response)) {
				// 如果响应直接是数组
				homeworkList.value = response.map(hw => ({
					...hw,
					// 为没有状态的作业设置默认状态
					status: hw.status || 'published'
				}))
			} else if (response && Array.isArray(response.data)) {
				// 如果响应是包含data属性的对象
				homeworkList.value = response.data.map(hw => ({
					...hw,
					status: hw.status || 'published'
				}))
			} else {
				// 处理非预期的响应格式
				homeworkList.value = []
				console.warn('作业列表数据格式不正确:', response)
			}
			console.log('作业列表数据加载成功:', homeworkList.value)
		} catch (error) {
			console.error('获取作业列表失败:', error)
			homeworkList.value = []
			ElMessage.error('获取作业列表失败')
		}
	}

	// 获取作业统计
	const fetchHomeworkStats = async () => {
		try {
			const response = await getHomeworkStats()
			// 处理统计数据的不同响应格式
			if (response && typeof response === 'object') {
				homeworkStats.value = response.data || response || {
					total: 0,
					graded: 0
				}
			} else {
				homeworkStats.value = {
					total: 0,
					graded: 0
				}
			}
		} catch (error) {
			console.error('获取作业统计失败:', error)
		}
	}

	// 页面加载时获取数据
	onMounted(() => {
		console.log('页面加载，开始获取作业数据')
		fetchHomeworkList()
		fetchHomeworkStats()
	})
</script>

<style scoped>
	.animate-blob {
		animation: blob 7s infinite;
	}

	.animation-delay-2000 {
		animation-delay: 2s;
	}

	.animation-delay-4000 {
		animation-delay: 4s;
	}

	@keyframes blob {
		0% {
			transform: translate(0px, 0px) scale(1);
		}

		33% {
			transform: translate(30px, -50px) scale(1.1);
		}

		66% {
			transform: translate(-20px, 20px) scale(0.9);
		}

		100% {
			transform: translate(0px, 0px) scale(1);
		}
	}

	/* 自定义上传组件样式 */
	:deep(.el-upload-dragger) {
		width: 100%;
		height: 150px;
	}

	:deep(.el-upload__tip) {
		margin-top: 8px;
		color: #909399;
		font-size: 12px;
	}

	/* 对话框样式优化 */
	:deep(.el-dialog__body) {
		padding: 20px 40px;
	}
</style>
